<template>
  <el-drawer
    @close="closeDialog"
    v-model="dialogVisible"
    :title="title"
    size="86%"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="60px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="标题" prop="infoName">
            <el-input
              :disabled="isDisabled"
              v-model="formData.infoName"
              :autosize="{ minRows: 4, maxRows: 4 }"
              type="textarea"
              show-word-limit
              maxlength="50"
              placeholder="请输入内容"
            />
          </el-form-item>
          <el-form-item label="来源" prop="infoOrigin">
            <el-input
              v-model="formData.infoOrigin"
              :disabled="isDisabled"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="类型" prop="isConnect">
            <el-select
              v-model="formData.isConnect"
              :disabled="isDisabled"
              style="width: 100%"
              @change="getIsConnect"
            >
              <el-option value="1" label="链接"></el-option>
              <el-option value="2" label="文本"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="链接"
            prop="infoContent"
            v-if="formData.isConnect == 1"
          >
            <el-input v-model="formData.infoContent" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item label="封面" prop="infoFileUrl">
            <el-upload
              :disabled="isDisabled"
              ref="uploadRef"
              class="avatar-uploader"
              :headers="{ 'x-auth-token': token }"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :action="`${baseURL}manage/v1/storage/upload?dir=videoDir`"
              :on-success="onUploadSuccess"
            >
              <el-image
                v-if="formData.infoFileUrl"
                :src="baseURL + formData.infoFileUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">封面建议宽高比2:1,不大于1M</div>
              </template>
            </el-upload>
          </el-form-item>

          <div class="footer">
            <el-button
              v-if="!isDisabled"
              @click="submitForm(ruleFormRef)"
              type="primary"
              :loading="submitLoading"
            >
              保存
            </el-button>
            <el-button @click="closeDialog">取消</el-button>
          </div>
        </el-col>
        <el-col :span="18">
          <el-form-item
            label="内容"
            prop="infoContent"
            v-if="formData.isConnect == 2"
          >
            <WangEditor
              :isDisabled="isDisabled"
              :initValue="formData.infoContent"
              @getEditorContent="onEditorChange"
            ></WangEditor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <template #footer>
      <div>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary"  @click="submitForm(ruleFormRef)">保存</el-button>
      </div>
    </template> -->
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules, UploadProps } from "element-plus";
import { baseURL } from "@/util/request";
import { ApiResult } from "@/util/request";
import { selectVideoList } from "@/api/videoManage.ts";
import WangEditor from "@/views/informationManage/informationList/components/wangEditor.vue";
import { saveOrUpdate } from "@/api/informationManage.ts";

interface IForm {
  id: string;
  infoContent: string;
  infoFileUrl: string;
  infoName: string;
  isConnect: string;
  infoOrigin: string;
}
const onEditorChange = (arr: any, html: any) => {
  formData.infoContent = html;
  console.log(html);
};
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  isDisabled: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
  parentMenuOption: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["update:visible", "update:data", "submit"]);

const ruleFormRef = ref();
const uploadRef = ref();
const videoTypeList = ref<any[]>([]);
const submitLoading = ref<boolean>(false);
const token = ref<string>(localStorage.getItem("x-auth-token"));

// localStorage.getItem

const formData = reactive<IForm>({
  id: "",
  infoContent: "",
  infoFileUrl: "",
  infoName: "",
  isConnect: "",
  infoOrigin: "",
});

//TODO 做成动态
const rules = reactive<FormRules<IForm>>({
  infoName: [{ required: true, message: "请输入", trigger: "blur" }],
  infoContent: [{ required: true, message: "请输入", trigger: "blur" }],
  infoFileUrl: [{ required: true, message: "请上传", trigger: "change" }],
  isConnect: [{ required: true, message: "请选择", trigger: "change" }],
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type.split("/")[0] !== "image") {
    ElMessage.error("只能上传图片!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error("图片不能大于1M");
    return false;
  }
  return true;
};

//TODO 做成动态
const title = computed(() => {
  return props?.data?.id ? (props?.isDisabled ? "详情" : "编辑") : "新增";
});

function clearUploadFile() {
  uploadRef.value?.clearFiles();
}

function getIsConnect() {
  formData.infoContent = "";
}

function onUploadSuccess(response: any) {
  if (response?.code != 200) {
    ElMessage.error(response?.msg || "上传错误！");
    clearUploadFile();
    return;
  }
  console.log(response);
  formData.infoFileUrl = response?.data?.fileUrl;

  ElMessage.success("上传完成！");
}
function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

async function getSelectVideoList() {
  const { success, msg, data } = await selectVideoList();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  videoTypeList.value = data;
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      result = await saveOrUpdate(formData);
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      ElMessage.success("操作成功");
      emit("submit");
      closeDialog();
    } else {
      console.log("error submit!", fields);
    }
  });
};
onMounted(async () => {
  await getSelectVideoList();
});
// watch(dialogVisible, (visible) => {
//   Object.keys(formData).forEach((key: any) => {
//     formData[key as keyof IForm] = visible ? props.data?.[key] || "" : "";
//     formData.isConnect = '2'
//   });
// });

watch(dialogVisible, (visible) => {
  console.log(111);
  console.log("props.data");
  console.log(props.data?.["infoContent"]);
  formData.id = props.data?.["id"];
  formData.infoContent = props.data?.["infoContent"];
  formData.infoFileUrl = props.data?.["infoFileUrl"];
  formData.infoName = props.data?.["infoName"];
  formData.isConnect = props.data?.["isConnect"];
  formData.infoOrigin = props.data?.["infoOrigin"];

  console.log("formData");
  console.log(formData.infoContent);
  // Object.keys(formData).forEach((key: any) => {
  //   console.log("props.data");
  //   console.log( props.data?.['infoContent']);

  //   formData[key as keyof IForm] = visible ? props.data?.[key] : "";
  //   formData.isConnect = '2'
  //   formData.infoContent = props.data?.['infoContent']

  // });
});
</script>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #999;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #999;
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 100px;
  text-align: center;
}
.avatar {
  width: 160px;
  height: 100px;
}
:deep(.w-e-text-container) {
  min-height: 200px;
  width: 100%;
}
.el-upload__tip {
  color: #999;
}
</style>
